package com.woodblockwithoutco.remotecontrollerexample;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;

public class MusicWatcherService extends Service implements Callback {
    private static final String TAG = MusicWatcherService.class.getSimpleName();
    private static final int CHECK_MUSIC_STATE_INTERVAL_MS = 1000;
    
    public static final String ACTION_MUSIC_STATE_CHANGED = ".action.MUSIC_STATE_CHANGED";
    public static final String EXTRA_STATE = ".extra.STATE";
    
    private static final int WHAT_CHECK_MUSIC = 0;
    private volatile boolean mKeepWatching;
    private AudioManager mAudioManager;
    private Handler mHandler;
    private volatile boolean mMusicActive;
    private LocalBroadcastManager mLocalBroadcastManager;
    
    @Override
    public void onCreate() {
        super.onCreate();
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        HandlerThread handlerThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND);
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper(), this);
        mMusicActive = false;
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mKeepWatching = true;
        mHandler.removeMessages(WHAT_CHECK_MUSIC);
        mHandler.sendEmptyMessage(WHAT_CHECK_MUSIC);
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public boolean handleMessage(Message msg) {
        boolean handled = false;
        switch (msg.what) {
            case WHAT_CHECK_MUSIC:
                handleCheckMusic();
                if (mKeepWatching) {
                    mHandler.sendEmptyMessageDelayed(WHAT_CHECK_MUSIC, CHECK_MUSIC_STATE_INTERVAL_MS);
                }
                handled = true;
                break;

            default:
                break;
        }
        return handled;
    }

    private void handleCheckMusic() {
        boolean musicActive = mAudioManager.isMusicActive();
        if (musicActive != mMusicActive) {
            mMusicActive = musicActive;
            Intent intent = new Intent(ACTION_MUSIC_STATE_CHANGED);
            intent.putExtra(EXTRA_STATE, musicActive);
            mLocalBroadcastManager.sendBroadcast(intent);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mKeepWatching = false;
        mHandler.removeMessages(WHAT_CHECK_MUSIC);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}
